package com.lc.projects.unit.thread.part02.test1;

public class Test1 {
	public static void main(String[] args) {
		Account account = new Account();
		account.setBalance(1000);
	
		Company company = new Company(account);
		Thread companyThread = new Thread(company);
		
		Bank bank = new Bank(account);
		Thread bankThread = new Thread(bank);
		System.out.println("Start:"+ account.getBalance());
		companyThread.start();
		bankThread.start();
		
	
		try {
			companyThread.join();
			bankThread.join();
			System.out.println("Final:"+ account.getBalance());
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		
		
		
	}
}

class Account {
	private double balance;

	public double getBalance() {
		return balance;
	}

	public void setBalance(double balance) {
		this.balance = balance;
	}

	public synchronized void addAmount(double amount) {
		double tmp = balance;
		try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		tmp += amount;
		balance = tmp;
	}

	public synchronized void substractAmount(double amount) {
		double tmp = balance;
		try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		tmp -= amount;
		balance = tmp;
	}

}

class Bank implements Runnable {

	public Bank(Account account) {
		super();
		this.account = account;
	}

	private Account account;

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			account.addAmount(1000);
		}
	}

}

class Company implements Runnable {
	

	public Company(Account account) {
		super();
		this.account = account;
	}

	private Account account;

	public Account getAccount() {
		return account;
	}

	public void setAccount(Account account) {
		this.account = account;
	}

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			account.substractAmount(1000);
		}
	}

}
